let express = require('express');
const axios = require('axios');
const FormData = require('form-data');
let router = express.Router();

const checkJWTMiddleWare = require('../middleWare/checkJWTMiddleWare');

// 此路由需要登录后才能访问
router.use(checkJWTMiddleWare);

const Response = require('../entity/http/Response');
const Img64 = require('../entity/file/Img64');
const wxCheck = require('../util/wx_check');

// 审核文字接口
router.post('/text', async function (req, res, next) {
    try {
        // 接收验证的文字
        let text = req.body.text;
        if (!text) return res.status(400).fail(400, '审核内容不允许为空');
        console.log('接收到的文字是', text);
        // 调用微信审核接口进行审核
        let access_token = await wxCheck.getAccessToken();
        try {
            const { data } = await axios.post(`https://api.weixin.qq.com/wxa/msg_sec_check?access_token=${access_token}`,
                { content: text },
                { headers: { 'Content-Type': 'application/json' } }
            );
            console.log('审核结果是', text, data);
            if (data.errcode == 0) {
                // 审核通过
                result = (new Response()).ok("审核通过");
            } else {
                result = (new Response()).fail(500, "信息中包含非法内容");
            }
        } catch (err) {
            result = (new Response()).fail(500, "信息中包含非法内容");
            console.log('审核报错', err);
        }
    } catch (err) {
        result = (new Response()).fail(500, "资源不可访问");
    }
    res.status(result.code).json(result);
});

// 审核图片接口
router.post('/img', async function (req, res, next) {
    try {
        // 接收图片
        let img = new Img64({ img: req.body.img });
        // 判断参数是否合法
        let flag = img.check();
        if (!flag.success) {
            return res.status(400).json(flag);
        }
        console.log('接受图片成功');
        // 组装 form-data
        const form = new FormData();
        form.append('media', img.buffer, {
            filename: 'check.jpg',
            contentType: 'image/jpeg'
        });
        console.log('构建 form 成功');
        try {
            // 发起审核请求
            let access_token = await wxCheck.getAccessToken();
            const { data } = await axios.post(`https://api.weixin.qq.com/wxa/img_sec_check?access_token=${ access_token }`,
                form,
                { headers: form.getHeaders() }
            );
            console.log('请求成功');
            if (data.errcode == 0) {
                result = (new Response()).ok("审核通过");
            } else {
                result = (new Response()).fail(500, "图片包含非法内容");
            }
        } catch (err) {
            result = (new Response()).fail(500, "图片包含非法内容");
            console.log('审核报错', err);
        }
    } catch (err) {
        console.log('审核图片接口报错', err);
        result = (new Response()).fail(500, "资源不可访问");
    }
    // 响应
    res.status(result.code).json(result);
});

module.exports = router;